<template>
  <div class="page_root" :key="queryUpdateFlag" data-page-name="关联任务(新)" data-page-identification="j_wrn0iw7moi">
    <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
      <!-- begin vid_ft9nivs6k8 自定义模板_k0736oxvzz -->
      <a-modal :visible="state.subVisible" title="请选择对应的子目标" centered @ok="submitTarget" @cancel="cancelTarget" :ok-button-props="{ loading: state.submitLoading }">
        <a-row>
          <a-radio-group v-model:value="state.subValue">
            <a-col :span="24" v-for="(item, index) in state.radioList" :key="index" style="margin-bottom: 16px">
              <a-radio :value="item.value">{{ item.label }}</a-radio>
            </a-col>
          </a-radio-group>
        </a-row>
      </a-modal>
      <div class="body">
        <div class="top-search">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="项目名称" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                <a-select
                  :options="state.projectList"
                  :filterOption="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                  mode="multiple"
                  show-search
                  @focus="getProject"
                  v-model:value="state.searchForm.projectCodeList"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-button @click="getTableData" type="primary"> 查询</a-button>
            </a-col>
          </a-row>
        </div>
        <div class="table-box">
          <a-table
            v-if="state.projectType === '交付' || state.projectType === '市场'"
            :columns="columns"
            :data-source="state.dataSource"
            bordered
            row-key="taskId"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
            :pagination="false"
            :scroll="{y:'600px'}"
          />
          <a-table
            v-else
            :columns="columns"
            :data-source="state.dataSource"
            bordered
            row-key="id"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
            :pagination="false"
          />
        </div>
        <div class="bottom-btn">
          <a-button type="primary" @click="showRadio">提交</a-button>
        </div>
      </div>
      <!-- end vid_ft9nivs6k8 自定义模板_k0736oxvzz -->
    </a-spin>
  </div>
</template>
<script setup lang="tsx">
  import {
      h, ref, reactive, toRaw, markRaw, watch, computed,
      onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
    } from "vue";
    import { useRoute, useRouter } from 'vue-router';
    const router = useRouter();
    const route = useRoute();
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
    import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission, getComponentParamsValue } from '@/utils/index';
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
    import dayjs from 'dayjs';
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
    import { message, notification, Modal } from 'ant-design-vue'
    import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
    import colorTheme from '@/design/custom-theme.json';
    
    import UserTableRecords from '@/model/UserTableRecords';
    import { getAppBaseUrl } from '@/utils/index';
    import { sendToken } from "@/hooks/useIframeToken";
    import { useSystemStore } from "@/store/modules/system";
    const systemStore = useSystemStore();
    



      // 获取传入的流程ID和组件参数
      const props = defineProps({
            'processInstanceId': {
            type: [String,Number,Boolean],
            default: undefined,
        },
      })
      const immediateWatch = (source, callback) => {
        watch(source, callback, {deep: true,immediate: true })
      }



  /* -------------------------- 属性定义 -------------------------- */

      const setTimeOutList = [];
      const pageLoading = reactive({
        loading: false,
        tip: undefined
      });
      const authInfo = localGet('app-user-store');




      // 处理校验
      const setSubFormName =(parentInfo, name)=>{
        return [parentInfo.parents, parentInfo.cycleIndex, name];
      }


  /* ========================== 属性定义 ========================== */


  /* -------------------------- 元素数据引用 -------------------------- */


  /* ========================== 元素数据引用 ========================== */


  /* -------------------------- 页面数据 -------------------------- */


  /* ========================== 页面数据 ========================== */



  /* -------------------------- 响应 -------------------------- */

  /* ========================== 响应 ========================== */


  /* -------------------------- 函数 -------------------------- */

  /* ========================== 函数 ========================== */


  /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
    })

  /* ========================== 页面参数 ========================== */


  /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================


  /* ========================== 组件事件处理方法 ========================== */


  /* -------------------------- 生命周期 -------------------------- */
  // 用于参数变更后重新执行自定义指令
      const queryUpdateFlag = ref(0);
      onMounted(() => { ;

    });

    onUnmounted(() => {
      // 销毁定时器
      setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ?  clearInterval(timer): clearTimeout(timer);
      });
    });

  /* ========================== 生命周期 ========================== */


  /* -------------------------- 数据关联处理 -------------------------- */





  /* -------------------------- 表单数据同步 -------------------------- */
  /* ========================== 表单数据同步 ========================== */

  /* ========================== 数据关联处理 ========================== */


  /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

  /* ========================== 不同组件自定义的处理逻辑 ========================== */


  // ================================定制化逻辑========================================
  onMounted(() => {
          const urlParams = new URLSearchParams(window.location.search)
          // 获取单个参数
          state.projectName = urlParams.get('projectName')
          state.projectType = urlParams.get('projectType')
          state.id = urlParams.get('id')
          if (state.projectType === '产品研发') {
              columns.value = [
                  {
                      title: '项目名称',
                      dataIndex: 'projectName'
                  },
                  {
                      title: '用户故事',
                      dataIndex: 'storyName'
                  },
                  {
                      title: '计划完成',
                      dataIndex: 'endTime'
                  },
                  {
                      title: '用户故事状态',
                      dataIndex: 'storyStatus'
                  }
              ]
          } else {
              columns.value = [
                  {
                      title: '项目名称',
                      dataIndex: 'projectCode'
                  },
                  {
                      title: '任务名称',
                      dataIndex: 'taskName'
                  },
                  {
                      title: '计划完成',
                      dataIndex: 'endTime'
                  },
                  {
                      title: '任务状态',
                      dataIndex: 'taskStatus'
                  }
              ]
          }
      })
      const state = reactive({
          searchForm: {
              projectCodeList: []
          },
          projectList: [],
          dataSource: [],
          projectName: undefined,
          projectType: undefined,
          id: undefined,
          selectedRowKeys: [],
          subVisible: false,
          submitLoading: false,
          radioList: [],
          subValue: undefined
      })
      const onSelectChange = selectedRowKeys => {
          state.selectedRowKeys = selectedRowKeys
      }
      const columns = ref([])
      function getProject() {
          post('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/platformProjectCodes', {
              projectName: state.projectName,
              projectType: state.projectType
          }).then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              state.projectList = data.data.projectCodeDtoList.map(item => {
                  return {
                      label: item.projectCode,
                      value: item.projectId
                  }
              })
          })
      }
      function getTableData() {
          const url =
              state.projectType === '产品研发'
                  ? '/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/storyByProjectId'
                  : '/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/tasksByProjectCode'
          post(url, {
              projectIdList: state.searchForm.projectCodeList,
              projectMonthlyGoalManagementId: state.id
          }).then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              state.dataSource =
                  state.projectType === '产品研发'
                      ? data.data.storyByProjectIdDtoList
                      : data.data.tasksByProjectCodeDtoList
          })
      }
      function showRadio() {
          console.log(state.selectedRowKeys)
          if (state.selectedRowKeys.length == 0) {
              message.info('请选择任务或用户故事')
              return
          }
          get(`/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/monthlyGoals/${state.id}`).then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              state.radioList = data.data.monthlyGoalObjectList.map(item => {
                  return {
                      label: item.monthlyGoal,
                      value: item.id
                  }
              })
              state.subVisible = true
          })
      }
      function cancelTarget() {
          state.subVisible = false
      }
      function submitTarget() {
          state.submitLoading = true
          if (state.projectType !== '产品研发') {
              post('/solution-ppm/api/v2/built-in-system-ppm/pmgf/upload/task', {
                  taskIdList: state.selectedRowKeys,
                  projectMonthlyGoalManagementId: state.id
              })
                  .then(data => {
                      if (data.code !== 200) {
                          message.error(data.message)
                          return
                      }
                      message.success(data.message)
                      cancelTarget()
                      getTableData()
                  })
                  .finally(() => {
                      state.submitLoading = false
                  })
          } else {
              post(`/solution-ppm/api/v2/built-in-system-ppm/pmgf/submit/relatedStory/${state.id}`, state.selectedRowKeys)
                  .then(data => {
                      if (data.code !== 200) {
                          message.error(data.message)
                          return
                      }
                      message.success(data.message)
                      cancelTarget()
                      getTableData()
                  })
                  .finally(() => {
                      state.submitLoading = false
                  })
          }
      }
</script>
<style lang="less" scoped>
  .page_root {
  width: 100%;
  height: 100%;
  overflow: auto;
  }
  .page_root :deep(.@{ant-prefix}-spin-nested-loading),
  .page_root :deep(.@{ant-prefix}-spin-container)
   {
      height: 100%;
  }
  .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper)
   {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
  }
  .page_root :deep(.@{ant-prefix}-table)
   {
    flex: auto;
    overflow: auto;
  }
  .table-moreBtn_down {
    overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
  }

  .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
    background: #ebf1ff;
  }

  /*  表格树结构样式处理，展开按钮层级增加*/
  :deep(.@{ant-prefix}-table-row-expand-icon) {
    z-index: 1;
  }
  /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
  :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 15px !important;
    width: calc(100% - 15px);
  }
  :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 30px !important;
    width: calc(100% - 30px);
  }
  :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 45px !important;
    width: calc(100% - 45px);
  }
  :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 60px !important;
    width: calc(100% - 60px);
  }

  /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
  :deep(.@{ant-prefix}-transfer-list)
   {
      height: 100%;
      width: 50%;
  }


  /*样式*/
      .page_root {
          overflow: hidden;
      }
      .body {
          position: relative;
          background-color: #fff;
          height: 100%;
          padding: 24px;
      }
      .table-box:deep(.@{ant-prefix}-table-thead) > tr > th {
          background: #3875ff;
          color: #fff;
          font-weight: 600;
          padding: 8px 16px;
          border-right: 1px solid #d9d9d9 !important;
          position: relative;
      }
      .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
          font-size: 14px;
          font-family: arial, helvetica, 'microsoft yahei';
          font-weight: 400;
          color: #262626;
          border-bottom: 1px solid #d9d9d9;
          padding: 8px 16px;
          word-break: break-all;
      }
      .bottom-btn {
          width: 100%;
          height: 60px;
          line-height: 30px;
          display: flex;
          justify-content: center;
          align-items: center;
          position: absolute;
          bottom: 0;
      }
      .modal-title {
          font-size: 14px;
          font-family: arial, helvetica, 'microsoft yahei';
          font-weight: 400;
          color: #262626;
          margin-bottom: 16px;
      }
      /*样式*/
</style>